package at.syncme.test;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Random;

/*
 * ClientTrafficSimulation.aj
 * 
 *  author: Daniel Rudigier
 *    date: 18.11.2008
 * 
 */

/**
 * try to simulate some game traffic from a client
 * 
 * @author Daniel Rudigier
 *
 */
public aspect ClientTrafficSimulationAspect {
    
    private long gameStart;
        
    pointcut GameStart(): call(framework.Game+.new());
    
    after() returning: GameStart() {
        this.gameStart = System.currentTimeMillis();
        System.out.println("cts: client traffic simulator started");
        new Thread(new ClientTrafficSimulation()).start();
    }
    
    private class ClientTrafficSimulation implements Runnable {

        /**
         * override
         *
         * @see java.lang.Runnable#run()
         */
        public void run() {
            Random r = new Random();
            
            try {
                Socket s = new Socket("localhost", 4711);
                
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                                
                while (true) {
                    int delay = Math.max(200, r.nextInt(3000));
                    //System.out.println("delay: " + delay);
                    
                    out.write(String.valueOf(System.currentTimeMillis() - gameStart));
                    out.write("\n");
                    out.flush();
                    
                    beLazy(delay);
                }
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        /**
         * @param i
         */
        private void beLazy(long msecs) {
            try {
                Thread.sleep(msecs);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
    }

}
